package com.huayi.order.repository;

import com.huayi.order.entity.ErpSalesOrderDetailVo;
import com.huayi.order.entity.SalesManEntity;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.PreparedStatementCreator;
import org.springframework.jdbc.support.GeneratedKeyHolder;
import org.springframework.jdbc.support.KeyHolder;
import org.springframework.stereotype.Repository;
import org.springframework.util.StringUtils;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;

@Repository
public class SalesManRepository {
    @Autowired
    private JdbcTemplate jdbcTemplate;

    /**
     * 列表
     * @param trueName
     * @param mobile
     * @return
     */
    public List<SalesManEntity> getList(String trueName,String mobile){
        String sql = "SELECT * FROM hy_sales_man WHERE 1=1 ";
        List<Object> params = new ArrayList<>();

        if(StringUtils.isEmpty(trueName)==false){
            sql += " AND true_name=?";
            params.add(trueName);
        }
        if(StringUtils.isEmpty(mobile)==false){
            sql += " AND mobile=?";
            params.add(mobile);
        }

        sql += " ORDER BY id DESC  ";

        return jdbcTemplate.query(sql, new BeanPropertyRowMapper<>(SalesManEntity.class), params.toArray(new Object[params.size()]));
    }


    /**
     * 添加
     * @param trueName
     * @param mobile
     * @param summary
     * @return
     */
    public Integer add(String trueName,String mobile,String summary){
        String sql = "INSERT INTO hy_sales_man (true_name,mobile,summary,add_time) VALUE (?,?,?,?)";
        KeyHolder keyHolder = new GeneratedKeyHolder();
        jdbcTemplate.update(new PreparedStatementCreator() {
            @Override
            public PreparedStatement createPreparedStatement(Connection connection) throws SQLException {
                PreparedStatement ps = connection.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS);
                ps.setString(1, trueName);
                ps.setString(2, mobile);
                ps.setString(3, summary);
                ps.setLong(4, System.currentTimeMillis() / 1000);
                return ps;
            }
        }, keyHolder);

        Integer id = keyHolder.getKey().intValue();
        return id;
    }
}
